<template>
  <el-upload
    class="upload-demo"
    :action="action"
    multiple
    :before-upload="beforeUpload"
    :data="data"
    :on-success="handleSuccess"
    :file-list="list"
    :on-remove="handleRemove"
    :on-preview="preview"
    accept=".pdf, .png, .doc, .jpg, .pptx, .docx, .xls, .xlsx"
  >
    <el-button type="primary">点击上传</el-button>
  </el-upload>
</template>

<script>
import API from '@/api/common/adjunct'
export default {
  props: {
    table_name: {
      type: String,
      default: ''
    },
    pk: {
      type: Number,
      default: 0
    },
    type: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      action: 'https://api.hx-im.com.cn/api/v1/adjunctAdd',
      list: []
    }
  },
  computed: {
    data() {
      return {
        table_name: this.table_name,
        id: this.pk,
        type: this.type
      }
    }
  },

  watch: {
    pk() {
      this.index()
    },
    type() {
      this.index()
    },
    table_name() {
      this.index()
    },
    list(newVal) {
      this.$emit('change', newVal)
    }
  },
  created() {
    this.index()
  },
  methods: {
    index() {
      API.index(this.data).then(response => {
        this.list = response.data.data
      })
    },
    handleSuccess(res) {
      console.log(res)
      this.$emit('category', res)
      this.list.push(res.data)
    },
    beforeUpload(file) {
      const isLt20M = file.size / 1024 / 1024 < 20
      if (!isLt20M) {
        this.$message.error('文件大小不能超过 20MB!')
      }
      return isLt20M
    },
    handleRemove(file, res) {
      this.$emit('del', file)
      API.delete(file.id)
      const index = this.list.findIndex(item => {
        if (item.id === file.id) {
          return true
        }
      })
      this.list.splice(index, 1)
    },
    preview(file) {
      window.open(file.path, 'hello')
    }
  }
}
</script>
